package com.aisino.inveli.vinda;

import com.aisino.inveli.vinda.utils.AlertUtil;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.IOException;

/**
 * @author leifeng
 * @Date 2017-11-09
 */
@SpringBootApplication
public class VindamanagerApplication extends Application  {

	private static ConfigurableApplicationContext springContext;
	private static Parent rootNode;
	public static Stage mainStage;

	public static void main(String[] args) {
		Application.launch(args);
	}

	@Override
	public void start(Stage primaryStage) throws Exception {
		mainStage = primaryStage;
		FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/main.fxml"));
		showView(fxmlLoader);
		mainStage.setOnCloseRequest(event -> {
			Boolean flag = AlertUtil.confirmAlert("确认退出",mainStage,"是否退出程序");
			if (flag) {
				Platform.exit();
				System.exit(0);
			}else{
				event.consume();
			}
		});
	}

	@Override
	public void init() throws Exception {
		springContext = SpringApplication.run(VindamanagerApplication.class);
	}

	public static FXMLLoader showView(FXMLLoader fxmlLoader)  {
		try {
			fxmlLoader.setControllerFactory(springContext::getBean);
			rootNode = fxmlLoader.load();
			mainStage.setScene(new Scene(rootNode));
			mainStage.setTitle("转换程序V17.11.13.beta.01");
			mainStage.getIcons().add(new Image("/image/icon.png"));
			mainStage.setResizable(false);
			mainStage.show();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fxmlLoader;
	}

	public static Stage showViewReturnStage(FXMLLoader fxmlLoader)  {
		try {
			fxmlLoader.setControllerFactory(springContext::getBean);
			rootNode = fxmlLoader.load();
			mainStage.setScene(new Scene(rootNode));
			mainStage.setTitle("转换程序V17.11.13.beta.01");
			mainStage.getIcons().add(new Image("/image/icon.png"));
			mainStage.setResizable(false);
			mainStage.show();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return mainStage;
	}
}
